// @ts-ignore
import md5 from 'js-md5';

export function generateSign(
  params: Record<string, any> | undefined,
  timestamp: number,
  method: 'get' | 'post',
  privateKey: string,
): string {
  let str = '';
  const allowKeys = new Set(['shopId', 'userId', 'oid', 'coid', 'dgOid', 'tagName']);

  if (method === 'get') {
    const signMap: Record<string, any> = {};
    if (params) {
      Object.keys(params).forEach((key) => {
        if (allowKeys.has(key)) signMap[key] = params[key];
      });
    }
    const ordered: Record<string, string> = {};
    Object.keys(signMap)
      .sort((a, b) => a.localeCompare(b))
      .forEach((k) => {
        if (signMap[k] !== null && signMap[k] !== undefined) ordered[k] = String(signMap[k]);
      });
    str = 'Timestamp' + timestamp + JSON.stringify(ordered) + privateKey;
  } else {
    const signMap: Record<string, any> = {};
    if (params) {
      Object.keys(params).forEach((key) => {
        const v = params[key];
        if (v !== null && v !== undefined && String(v) !== 'NaN' && allowKeys.has(key)) {
          signMap[key] = v;
        }
      });
    }
    const ordered: Record<string, string> = {};
    Object.keys(signMap)
      .sort((a, b) => a.localeCompare(b))
      .forEach((k) => {
        if (signMap[k] !== null && signMap[k] !== undefined) ordered[k] = String(signMap[k]);
      });
    str = 'Timestamp' + timestamp + JSON.stringify(ordered) + privateKey;
  }
  // @ts-ignore
  return md5(str).toUpperCase();
}


